<template>
    <div class="box">
        <div id="container"></div>
        <div id="panel">
            <div id="info">当前点击坐标为：<span id="position"><span v-show="lat && lng">{{ this.lat }},{{ this.lng }}</span></span>
            </div>
            <div class="search">
                <el-input id='keyword' :disabled="isdisabled" v-model='keyword' @input="getSuggestions()" @focus="focus"></el-input>
                <el-button id="search"  :disabled="isdisabled" class="btn" @click="searchByKeyword()">搜索</el-button>
            </div>
            <div id="suggestionList">
                <div class="item" v-for="(item, index) in suggestionList" :key="index"
                    @click="setSuggestion(index, item.address)">
                    {{ item.title }}
                </div>
                <!-- {{ item.address }} -->
            </div>
        </div>

    </div>
</template>

<script>
export default {
    data() {
        return {
            keyword: "",
            map: null,
            markerLayer: null,
            search: null,
            suggest: null,
            suggestionList: [],
            infoWindowList: Array(10),
            infoWindow: null,
            geometries: null,
            geocoder: null,
            lat: "",
            lng: "",
			// isdisabled:false,
        }
    },
    props: {
        location: Object,
		isdisabled:{
			type:Boolean,
			default:false
		}
    },
    watch: {
        lat: {
            deep: true,
            handler: function () {
                this.$emit('update:location', {
                    lat: this.lat,
                    lng: this.lng
                })
            }
        },
        location: {
            immediate: true,
            deep: true,
            handler: function () {
                this.lat = this.location?.lat
                this.lng = this.location?.lng
                setTimeout(() => {
                    this.convertf()
                }, 2000);
            }
        }
    },
    methods: {
        initMap() {
            //定义地图中心点坐标
			
            var center = new TMap.LatLng(28.692306, 115.868225)
            //定义map变量，调用 TMap.Map() 构造函数创建地图
            this.map = new TMap.Map("container", {
                center: center,//设置地图中心点坐标
                zoom: 13,   //设置地图缩放级别
                pitch: 43.5,  //设置俯仰角
                rotation: 45    //设置地图旋转角度
            });
            this.markerLayer = new TMap.MultiMarker({
                id: 'marker-layer',
                map: this.map,
                geometries: [],
            });


            this.map.on("click", (evt) => {
                this.lat = evt.latLng.lat;
                this.lng = evt.latLng.lng;
                console.log(evt)
                this.convertf()
                // position.innerHTML = lat + "," + lng;

                //移除标点
                this.markerLayer.setMap(null);
                this.markerLayer = null;
                if (!this.markerLayer) {
                    this.markerLayer = new TMap.MultiMarker({
                        id: 'marker-layer',
                        map: this.map,
                        geometries: [],
                    });
                }
                // 添加标点
                this.markerLayer.add({
                    position: evt.latLng
                });
                this.suggestionList = null
            })
            this.search = new TMap.service.Search({ pageSize: 10 });// 新建一个地点搜索类
            // 搜索

            this.suggest = new TMap.service.Suggestion({
                // 新建一个关键字输入提示类
                pageSize: 10, // 返回结果每页条目数
                region: '江西', // 限制城市范围
                regionFix: true, // 搜索无结果时是否固定在当前城市
            });
			
            this.geocoder = new TMap.service.Geocoder(); // 新建一个正逆地址解析类

        },
        // 使用者在搜索框中输入文字时触发
        getSuggestions() {
            this.suggestionList = null
            if (this.keyword) {
                this.suggest.getSuggestions({ keyword: this.keyword, location: this.map.getCenter() })
                    .then((res) => {
                        // 以当前所输入关键字获取输入提示
                        this.suggestionList = null
                        this.suggestionList = res.data;

                    })
                    .catch((error) => {
                        console.log(error);
                    });
            }
        },
        // 点击输入提示后，于地图中用点标记绘制该地点，并显示信息窗体，包含其名称、地址等信息
        setSuggestion(index, address) {
            this.convert(address)

            this.infoWindowList.forEach((infoWindow) => {
                infoWindow.close();
            });
            this.infoWindowList.length = 0;
            this.keyword = this.suggestionList[index].title;
            this.markerLayer.setGeometries([]);
            this.markerLayer.updateGeometries([
                {
                    id: '0', // 点标注数据数组
                    position: this.suggestionList[index].location,
                },
            ]);
            var infoWindow = new TMap.InfoWindow({
                map: this.map,
                position: this.suggestionList[index].location,
                content: `<h3>${this.suggestionList[index].title}</h3><p>地址：${this.suggestionList[index].address}</p>`,
                offset: { x: 0, y: -50 },
            });
            this.infoWindowList.push(infoWindow);
            this.map.setCenter(this.suggestionList[index].location);
            this.markerLayer.on('click', (e) => {
                this.infoWindowList[Number(e.geometry.id)].open();
            });
        },
        // 关键字搜索功能
        searchByKeyword() {
            this.infoWindowList.forEach((infoWindow) => {
                infoWindow.close();
            });
            this.infoWindowList.length = 0;
            this.markerLayer.setGeometries([]);
            this.search.searchRectangle({
                keyword: this.keyword,
                bounds: this.map.getBounds(),
            })
                .then((result) => {
                    result.data.forEach((item, index) => {
                        var geometries = this.markerLayer.getGeometries();
                        var infoWindow = new TMap.InfoWindow({
                            map: this.map,
                            position: item.location,
                            content: `<h3>${item.title}</h3><p>地址：${item.address}</p><p>电话：${item.tel}</p>`,
                            offset: { x: 0, y: -50 },
                        });
                        infoWindow.close();
                        this.infoWindowList[index] = infoWindow;
                        geometries.push({
                            id: String(index),
                            position: item.location,
                        });
                        this.markerLayer.updateGeometries(geometries);
                        this.markerLayer.on('click', (e) => {
                            this.infoWindowList[Number(e.geometry.id)].open();
                        });
                    });
                });
        },
        // 地址转坐标
        convert(address) {
            // 将给定的地址转换为坐标位置
            this.geocoder.getLocation({ address })
                .then((result) => {
                    this.map.setCenter(result.result.location);
                    let weizi = result.result.location.toString();
                    this.lat = weizi.split(",")[0]
                    this.lng = weizi.split(",")[1]
                    // 显示坐标数值
                });
        },
        // 坐标转地址
        convertf() {
            var location = new TMap.LatLng(Number(this.lat), Number(this.lng));
            this.map.setCenter(location);
            this.geocoder
                .getAddress({ location: location }) // 将给定的坐标位置转换为地址
                .then((result) => {
                    //    this.keyword = result.result.address;
                    this.keyword = result.result.formatted_addresses.recommend
                    // 显示搜索到的地址
                });
        },
        focus() {
            this.getSuggestions()
        }
    },
    mounted() {
        this.initMap()
    }
}
</script>

<style lang="scss" scoped>
.box {
    width: 100%;
    height: 100%;
    position: relative;

    /*地图(容器)显示大小*/
    #container {
        width: 100%;
        height: 100%;
    }

    // 搜索
    #panel {
        position: absolute;
        width: 350px;
        z-index: 9999;
        top: 5%;
        left: 5%;

        // 坐标位置
        #info {
            width: 100%;
            font-size: 14px;
            background: #FFF;
            padding: 10px;
            box-sizing: border-box;
            border-radius: 3px;
            margin-bottom: 10px;
        }

        .search {
            width: 100%;
            display: flex;
            justify-content: center;
            align-items: center;

            #keyword {
                width: 100%;
            }

            .btn {
                margin-left: 10px;
            }
        }

        #suggestionList {
            width: 100%;
            box-sizing: border-box;
            background-color: #fff;
            border: 1px solid #f2f2f2;
        }

        .item {
            height: 30px;
            overflow: hidden;
            display: flex;
            align-items: center;

            &:hover {
                background-color: aqua;
            }
        }



    }



}
</style>